import React from 'react';
import { Button } from 'antd';
import { WeaTop, WeaDialog, WeaFormItem, WeaSearchGroup, WeaTools, WeaSelect, WeaAlertPage, WeaLocaleProvider  } from 'ecCom';
import { inject, observer } from 'mobx-react';
import { WeaTableNew, WeaSwitch, WeaLogView,  } from 'comsMobx';
import { toJS } from 'mobx';

import { doPrint, doIFramePrint } from './print';
const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;

@inject('seatCardStore')
@observer
class PrintPreview extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      printPreviewVisible: false,
      previewVisible: true,
      printSetSelectVal: 1,
    }
  }

  componentDidMount() {
    const { getPrintUp, getBeforePrintInfo } = this.props.seatCardStore;
    getPrintUp();
  }

  getSearchs = (form, conditions) => {
    if (!form) return;
    const { isFormInit } = form;
    const { printSetSelectVal } = this.state;
    let group = [];
    let col = 1;
    const formParams = form.getFormParams();
   
    isFormInit && conditions && conditions.map((c, index) => {
      let items = [];
      c.items.map(fields => {
          items.push({
            com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@5ecnlv@${fields.domkey[0]}`}
              label={`${fields.label}` }
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
              error={form.getError(fields)}
            >
              {<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@yyaa1a@${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} />}
            </WeaFormItem>),
            col: col,
            hide: form.isHide(fields, (keys, allParams) => {
              let bool = false;
              getKey(fields) === 'sizeShow' && (allParams.doubleSideShow === '1') && (bool =true)
              return bool;
            })
          })
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@s6uz2g@${index}`} needTigger={true} showGroup={true} items={items} />);
    });
    return group;
  }


  getPrintSet = () => {
    const { printSetVisible, setState, setForm, setConditions } = this.props.seatCardStore;
    let btns = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@87mj4s@doSubmit`} type="primary" onClick={() => { setState({ printSetVisible: false }) }}>{getLabel(382958,'确定')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@dmr2gl@doCancel`} type="ghost" onClick={() => { setState({ printSetVisible: false });setForm.reset(); }}>{getLabel(201,"取消")}</Button>,
    ];
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@fz4vxb`}
        title={getLabel('20756','打印设置')}
        icon='icon-coms-meeting'
        iconBgcolor='#F14A2D'
        visible={printSetVisible}
        style={{ width: 600, height: 300 }}
        onCancel={() => setState({ printSetVisible: false })}
        buttons={btns}
      >
        { this.getSearchs(setForm, setConditions) }
      </WeaDialog>
    );
  }

  replaceString = (info, templet) => {
    if (!info || !templet) return;
    let temp = templet;
    Object.keys(info).forEach(key => {
      let str = `\\#\\[${ key }\\]`;
      let reg = new RegExp(str, "g");

      if (info[key] && info[key].indexOf("<span style='display:inline-block'></span>") > -1) {
        let s = `#[${key}]`;
        let arr = temp.split(s);
        let firstLoc = arr[0] ? arr[0].lastIndexOf('>') : '';
        let lastLoc = arr[1] ? arr[1].indexOf('<') : '';
        let firstString = arr[0] ? arr[0].substring(firstLoc+1, arr[0].length) : '';
        let lastString = arr[1] ? arr[1].substring(0, lastLoc) : '';
  
        if (arr[0]) {
          if (firstString === '') {
            temp = arr[0] + "<span style='display:inline-block'></span>";
          } else {
            temp = arr[0].substring(0, firstLoc) + "<span style='display:inline-block'></span>";
          }
        }
        
        if (arr[1]) {
          if (lastString === '') {
            temp = temp + arr[1];
          } else {
            temp = temp + arr[1].substring(lastLoc, arr[1].length);
          }
        }
      } else {
        temp = temp.replace(reg, info[key])
      }
    });
    return temp;
  }

  setPrintStyle = (printContents, printNum, doubleSideShow, templet ) => {
    if (printContents === undefined || printContents && printContents.length === 0) {
      return (
        <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@640g1k`} icon="icon-blog-blank">
          {getLabel(83553,"暂无数据")}
        </WeaAlertPage>
      );
    }
    if (printContents && Array.isArray(printContents)) {
      const { setForm } = this.props.seatCardStore;
      let fields = [];
      let group = [];
      let printHeight = doubleSideShow === '1' ? 1000 : printNum == 3 ? 1035 : 1000;
      if(printContents && printContents.length === 3 && printNum === 3 ) {
        printHeight = 1025;
      }
      let X = setForm.getFormParams().X || 0, Y = setForm.getFormParams().Y || 0;
      let contentStyle = { border: '0px solid #888', margin: '0px 0px', height: printHeight, position: 'relative' };
      X = parseInt(X, 10);
      Y = parseInt(Y, 10);
      let A4Height = printHeight;
      let style = { height: A4Height / printNum, };
      let cutoffStyle = {
        borderBottom:  '1px dashed #888',
        position: 'absolute',
        width: '100%',
      };
      let XY = {
        paddingTop: Y,
        paddingLeft: X,
      };
      let _XY = {
        paddingTop: Y,
        paddingLeft: X,
      }
      printContents.map((res, i) => {
        let string = this.replaceString(res, templet);
        if (doubleSideShow === '1') { // 双面打印
          let h = printHeight / 2 ;
          group.push(
            <div className='card-container' style={{ ...contentStyle }}>
              <div className='card-content' style={{ ..._XY, height: h, transform: 'rotate(180deg)',  boxSizing: 'border-box', borderTop: '0px dashed #888', borderBottom: '0px dashed #888' }} dangerouslySetInnerHTML={{ __html: string }}></div>
              <div className="" style={{ width: '100%', borderBottom: '1px dashed #888' }}></div>
              <div className='card-content' style={{ ...XY, height: h, borderTop: '0px dashed #888',  boxSizing: 'border-box', borderBottom: '0px dashed #888' }} dangerouslySetInnerHTML={{ __html: string }}></div>
            </div>,
            <div className="noprint"  style={{ width: '100%', borderBottom: '1px solid #888'}}></div>,
            <div style={{ pageBreakAfter: 'always' }}></div>
          );
        } else {
          let count = i+1;
         
          if (count % printNum === 0) { // 每页第1张
            style =  {
              ...XY,
              height: A4Height / printNum,
            };
            if (printNum == 2) {
              style =  {
                ...style,
                // borderBottom: '1px dashed #888',
              };
            }
            printNum == 3 && fields.push(
              <div style={{ ...cutoffStyle, top: 0 }}></div>,
            );
            fields.push(
              <div className='card-content' style={{ ...style, boxSizing: 'border-box' }} dangerouslySetInnerHTML={{ __html: string }}></div>,
            );
            
            } else { // 每页非第1张
              if (count % printNum === 1) {
                style = {
                  ...XY,
                  height: A4Height / printNum,
                  borderTop: printNum == 3 ? '1px dashed #888' : '',
                };
              } else {
                printNum !== 1 ? style = { 
                  ...XY,
                  height: A4Height / printNum,
                  borderTop: printNum == 3 ? '1px dashed #888' : ''
                } : ''
              }
              fields.push(
                <div className='card-content' style={{ ...style, boxSizing: 'border-box' }} dangerouslySetInnerHTML={{ __html: string }}></div>,
              );
              fields.push(
                <div  className={printNum == 2 ? '' : ""} style={{ ...cutoffStyle, top: (count%printNum)*(A4Height / printNum) }}></div>,
              );
          }
          if (count % printNum === 0) {
            group.push(
              <div className='card-container' style={{ ...contentStyle }}>
                {fields}
              </div>,
              <div className={printNum == 3 ? '' : "noprint"} style={{ width: '100%', borderBottom: printNum == 3 ? '1px dashed #888' : '1px solid #888' }}></div>,
              <div style={{ pageBreakAfter: 'always' }}></div>,
            );
            fields = [];
          } else {
            if (count === printContents.length) { // 最后一页最后一张图
              group.push(
                <div className='card-container' style={{ ...contentStyle }}>
                  {fields}
                </div>
              );
              fields = [];
            }
          }
        }
      });

      return group;
    }
  }

  render() {
    const { previewVisible, previewContent } = this.state;
    let { seatCardVisible, setState, printPreviewVisible, setForm, getPrintUp, mouldcontent, hrmInfo } = this.props.seatCardStore;
    let doubleSideShow = setForm.getFormParams().doubleSideShow;
    let number = parseInt(setForm.getFormParams().sizeShow, 10) || 1;
    hrmInfo = toJS(hrmInfo);
    let btns = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@swl7rz@printSetting`} type="primary" onClick={() => {
        getPrintUp();
        setState({ printSetVisible: true });
      }}>{getLabel('20756','打印设置') }</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3slk9m@print`} type="primary" disabled={hrmInfo === undefined || hrmInfo&&hrmInfo.length === 0} onClick={() => {
        let printId = 'print-seat-card-container';
        doIFramePrint(printId);
      }}>{getLabel('257','打印')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@in07oz@doClose`} type="ghost" onClick={() => setState({ printPreviewVisible: false })}>{getLabel(130711,"关闭")}</Button>
    ];

    return (
      previewVisible ? <div className='seat-card-templet-print-dialog'>
        {<div className='seat-card-templet-print-dialog-content'>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@phluxc`}
            title={getLabel('512438','打印席卡') }
            icon={<i className="icon-coms-meeting" />}
            iconBgcolor="#F14A2D"
            buttons={btns}
            showDropIcon={true}
          >
            <div id="print-seat-card-container" className='print-seat-card-container_pre' style={{ overflow: 'auto', height: '100%' }}>
              { this.setPrintStyle(hrmInfo, number, doubleSideShow, mouldcontent) }
            </div>
          </WeaTop>
        </div>}
        {this.getPrintSet()}
      </div>
        :
        ''
    );
  }
}

export default PrintPreview;